package com.itheima.config;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * <h1>ysm</h1>
 *
 * @author <a href="11n_yd2h5e1jx8@dingtalk.com">叶世铭</a>
 * @since 2023/2/6
 */
//@Configuration
public class ThreadPoolTaskSchedulerConfig implements SchedulingConfigurer {

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
        ThreadPoolTaskScheduler threadPoolTaskScheduler
                = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(5);
        threadPoolTaskScheduler.initialize();
        return threadPoolTaskScheduler;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        int maxPoolSize = 4;
        int corePoolSize =(scheduledTaskRegistrar.getCronTaskList().size() > maxPoolSize) ? maxPoolSize : scheduledTaskRegistrar.getCronTaskList().size();
        ScheduledExecutorService scheduledExecutorService
                = new ScheduledThreadPoolExecutor(corePoolSize,new BasicThreadFactory.Builder().namingPattern("******").daemon(true).build());
        scheduledTaskRegistrar.setScheduler(scheduledExecutorService);
    }
}
